import axios, { AxiosResponse, Method } from "axios";
import { IR } from '@/interface/Irequest';
import createPinia from '@/pinia';
import LoadingStroke from '@/pinia/loading';
import { NotificationError } from "./message";

const loading = LoadingStroke(createPinia);
const request = axios.create({
  timeout: 500,
  baseURL: import.meta.env.VITE_BASE_URL
});

request.interceptors.request.use((config) => {
  loading.increment();
  return config;
}, error => {
  loading.decrement();
  console.log(error);
  NotificationError("请求错误", error);

})

request.interceptors.response.use((res: AxiosResponse<IR<any>, any>) => {
  loading.decrement();
  if (res.data.code === 200) {
    return res;
  }

  return res;
}, error => {
  loading.decrement();
  NotificationError("响应错误", error ?? "");
  throw new Error(error);
})

/**
 * 请求处理
 * @param method 请求类型
 * @param url 请求路径
 * @param data 请求参数
 * @param option 选项
 * @returns IR<R> {data,success,error}
 */
export function requestHandler<R, T = {}>(method: Method, url: string, data?: T, option?: { [key: string]: string }): Promise<IR<R>> {
  const res = request<IR<R>>({
    url,
    method,
    data,
    ...option,
  });

  return Promise.resolve(res.then(res1 => res1.data))
}





export default request;